package com.gexin.controller.system.order;

import com.alipay.AlipaySDK;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.gexin.common.AppConst;
import com.gexin.common.WebConst;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.AjaxCmd;
import com.gexin.common.utils.IdGenerateUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.order.*;
import com.gexin.model.product.Products;
import com.gexin.model.shop.ShopInfo;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.weixin.uitls.WxConfig;
import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.PaymentApi;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 * @author 方俊逸 2016-06-22
 *
 */

@ControllerBind(controllerKey = "/system/order", viewPath = "WEB-INF/system/order")
public class OrderController extends SystemBaseController {
	private static Log log = Log.getLog(OrderController.class);

	public void push_order() {
		String sql = "	SELECT o.id,o.interface_state,o.interface_time,addr.province_id,o.state,addr.city_id,addr.area_id,addr.address,addr.receive_name,addr.phone from t_order as o,t_user_address as addr where o.id=? and  o.state=1 and o.interface_state in(1,97)   and o.address_id=addr.id  ";
		Order o = Order.dao.findFirst(sql, getPara());
		if (o == null) {
			success();
			// fail("订单状态不符合，或者不存在！");
			return;
		}
		Order_Extends e = new Order_Extends();
		e.setArea_id(o.getStr("area_id"));
		e.setProvince_id(o.getStr("province_id"));
		e.setCity_id(o.getStr("city_id"));
		e.setAddress(o.getStr("address"));
		e.setReceive_name(o.getStr("receive_name"));
		e.setPhone(o.getStr("phone"));
		OrderItem item = OrderItem.dao.getOrderItemByOrderId(o.getId());
		e.setSkuid(item.getSkuCode());
		e.setGoodsnumber(item.getNums());
		e.setGoodsid(Products.dao.findByIdLoadColumns(item.getProductId(), "source_product_id").getSourceProductId());
		e.setOrder_id(o.getId());
		Order new_o = new Order();
		new_o.setId(o.getId());
		new_o.setInterfaceState(2);
		new_o.setInterfaceTime(new Date());
		new_o.update();
		// String json = JsonKit.toJson(e);
		log.info("推送手动下单：" + e.getOrder_id());
		Redis.use().lpush(Cache_Order.Cache_Push_Order, e);// 推送订单
		success();
	}

	// 退款详细信息
	public void refund_detail() {
		OrderItem item = OrderItem.dao.getOrderItemById(getPara());
		setAttr("item", item);
		Order o =Order.dao.findById(item.getOrderId());
		setAttr("order",o);
		setAttr("user", WeixinUser.dao.findById(o.getUserId()));
		OrderRefundApply refund = OrderRefundApply.dao.getOrderRefundApplyByItemId(getPara());
		if (StringUtil.isNotBlank(refund.getStr("refund_img"))) {
			refund.put("img", refund.getRefundImg().split(","));
		}
		if (StringUtil.isNotBlank(refund.getStr("refund_express_img"))) {
			refund.put("express_img", refund.getRefundExpressImg().split(","));
		}
		setAttr("refund", refund);
		setAttr("shop", ShopInfo.dao.findById(ShopInfo.shop_id));
		render("order_refund_detail.html");
	}

	/**
	 * xu 2016-08-01 维权订单
	 */
	public void refundList() {
		log.info("维权订单");
		// 首先取到所以的订单状态
		Order order = getModel(Order.class, "order");
		setAttr("order", order);
		// 如果有状态 ,就返给前端 ,设置activity
		List<OrderState> state_list = OrderState.dao.cache_GetStateList();
		setAttr("state_list", state_list);
		// 根据shop_id 取到所有的大订单 和小订单
		paginate(Order.dao.refundPaginate(ShopInfo.shop_id, order, getPara("start_time", null), getPara("end_time", null), getpage(), WebConst.Page_Size, getParaToInt("refund", 0)));
		List<Order> order_list = Order.dao.refundPaginate(ShopInfo.shop_id, order, getPara("start_time", null), getPara("end_time", null), getpage(), WebConst.Page_Size, getParaToInt("refund", 0)).getList();
		for (int i = 0; i < order_list.size(); i++) {
			List<OrderItem> item_list = OrderItem.dao.getOrderItemsByOrderId(order_list.get(i).getId());
			order_list.get(i).put("item", item_list);
		}
		setAttr("refund", getParaToInt("refund", 0));
		setAttr("start_time", getPara("start_time", null));
		setAttr("end_time", getPara("end_time", null));
		setAttr("order_list", order_list);
		render("order_refund_list.html");
	}

	// 订单列表 fang 2016-06-22
	public void index() {
		log.info("订单列表");
		// 首先取到所以的订单状态
		Order order = getModel(Order.class, "order");
		order.put("product_id", getParaToInt("product_id", null));
		setAttr("order", order);
		// 如果有状态 ,就返给前端 ,设置activity
		List<OrderState> state_list = OrderState.dao.cache_GetStateList();
		setAttr("state_list", state_list);
		// 根据shop_id 取到所有的大订单和小订单
		Page<Order> page = Order.dao.paginate(ShopInfo.shop_id, order, getPara("start_time", null), getPara("end_time", null), getpage(), WebConst.Page_Size);
		for(Order o:page.getList()){
			// 黎峻
			if(o.getType()==2){
				OrderPresale is_sf=OrderPresale.dao.findByOrderIdAndType(o.getId(),1);//查订金
				OrderPresale is_wk=OrderPresale.dao.findByOrderIdAndType(o.getId(),2);//查尾款
				if(is_sf.getState()==1){
					o.put("is_presale_state",1);
				}else if(is_sf.getState()==2 && is_wk.getState()==1){
					o.put("is_presale_state",2);
				}else{
					o.put("is_presale_state",3);
				}
			}else{
				o.put("is_presale_state",3);
			}
		}
		paginate(page);
		List<Order> order_list = page.getList();
		for (int i = 0; i < order_list.size(); i++) {
			List<OrderItem> item_list = OrderItem.dao.getOrderItemsByOrderId(order_list.get(i).getId());
			order_list.get(i).put("item", item_list);
		}
		setAttr("start_time", getPara("start_time", null));
		setAttr("end_time", getPara("end_time", null));
		setAttr("order_list", order_list);
		setAttr("product_list", Products.dao.getAllProductsByShop_id(ShopInfo.shop_id));// 查询所有的商品
		render("order_list.html");
	}
	
	public void orderListQuery() {
		Order order=new Order();
		order.setState(getParaToInt("state"));
		order.setOrderPlatform(getParaToInt("orderPlatform"));
		order.setExpressReceiveName(getPara("expressReceiveName"));
		order.setId(getPara("id"));
		order.setExpressPhone(getPara("expressPhone"));
		order.put("product_id", getParaToInt("productId", null));
		Page<Order> page = Order.dao.paginate(ShopInfo.shop_id, order, getPara("startTime", null), getPara("endTime", null), getpage(), WebConst.Page_Size);
		for (Order obj : page.getList()) {
			// 黎峻
			if(obj.getType()==2){
				OrderPresale is_sf=OrderPresale.dao.findByOrderIdAndType(obj.getId(),1);//查订金
				OrderPresale is_wk=OrderPresale.dao.findByOrderIdAndType(obj.getId(),2);//查尾款
				if(is_sf.getState()==1){
					obj.put("is_presale_state",1);
				}else if(is_sf.getState()==2 && is_wk.getState()==1){
					obj.put("is_presale_state",2);
				}else{
					obj.put("is_presale_state",3);
				}
			}else{
				obj.put("is_presale_state",3);
			}
			List<OrderItem> item_list = OrderItem.dao.getOrderItemsByOrderId(obj.getId());
				for (OrderItem orderItem : item_list) {
					orderItem.put("refund_state_name", AppConst.Refund_State.get(orderItem.getRefundState()));
					orderItem.put("refund", OrderRefund.dao.findByItemId(orderItem.getItemId()));
				}
			obj.put("item",item_list);
			obj.put("order_platform_name", AppConst.Order_Platform.get(String.valueOf(obj.getOrderPlatform())));
			obj.put("interface_state_name", AppConst.Pdd_Interface_State.get(obj.getInterfaceState()));
		}
		renderJson(page);
	}
	
	// 订单退款
	public void refund() {
		String order_id = getPara();
		if (StringUtil.isBlank(order_id)) {
			fail("订单不能为空！");
			return;
		}
		try {
			AjaxCmd cmd = Order.dao.refund(order_id, 1);
			renderJson(cmd);
		} catch (Exception e) {
			fail("操作失败，请稍后再试！");
		}
	}

	// 订单退款
	public void qiangzhi_refund() {
		String order_id = getPara();
		if (StringUtil.isBlank(order_id)) {
			fail("订单不能为空！");
			return;
		}
		try {
			AjaxCmd cmd = Order.dao.refund(order_id, 2);
			renderJson(cmd);
		} catch (Exception e) {
			fail("操作失败，请稍后再试！");
		}
	}

	// 指定金额退款
	public void zhiding_refund() {
		String order_id = getPara();
		BigDecimal price = new BigDecimal(getPara("price"));
		if (StringUtil.isBlank(order_id)) {
			fail("订单不能为空！");
			return;
		}
		if (price.doubleValue() <= 0) {
			fail("金额不对！");
			return;
		}
		try {
			AjaxCmd cmd = Order.dao.refund(price, order_id);
			renderJson(cmd);
		} catch (Exception e) {
			fail("操作失败，请稍后再试！");
		}
	}

	// 订单详情 fang 2016-06-24
	public void detail() {
		//
		Order order = Order.dao.getOrderDetailById(getPara());
		List<OrderItem> item_list = OrderItem.dao.getOrderItemsByOrderId(getPara());
		for (OrderItem orderItem : item_list) {
			orderItem.put("refund_state_name", AppConst.Refund_State.get(orderItem.getRefundState()));
			orderItem.put("refund", OrderRefund.dao.findByItemId(orderItem.getItemId()));
		}
		//优惠金额
		BigDecimal preferentialAmount=BigDecimal.ZERO;
		
		//优惠卷不为空 优惠金额加上优惠卷金额
		if (order.getCouponId()!=null) {
			preferentialAmount=preferentialAmount.add(order.getCouponAmount());
		}
		//兑换码不为空 优惠金额加上兑换码金额
		if (order.getPromoCode()!=null) {
			preferentialAmount=preferentialAmount.add(order.getPromoMoney());
		}
		//订单首件立减总额不为空 优惠金额加上立减总额
		if (order.getFirstDiscountMoney()!=null) {
			preferentialAmount=preferentialAmount.add(order.getFirstDiscountMoney());
		}
		//订单第二件立减总额不为空 优惠金额加上立减总额
		if (order.getSecondMoney()!=null) {
			preferentialAmount=preferentialAmount.add(order.getSecondMoney());
		}

		// 黎峻
		if(order.getType()==2){
			OrderPresale is_sf=OrderPresale.dao.findByOrderIdAndType(order.getId(),1);//查订金
			if(is_sf.getState()!=2){
				order.put("is_presale_state",1);
			}else{
				order.put("is_presale_state",2);
				order.put("time",is_sf.getCreateTime());
			}
			OrderPresale is_wk=OrderPresale.dao.findByOrderIdAndType(order.getId(),2);//查尾款
			if(is_wk.getState()!=2){
				order.put("is_presale_state",3);
			}else{
				order.put("is_presale_state",4);
				order.put("time",is_wk.getCreateTime());
			}
		}

		order.put("preferentialAmount",preferentialAmount);
		setAttr("order", order);
		setAttr("item_list", item_list);
		render("order_detail.html");
	}

	/**
	 * fang 2016-06-22 注意: 根据 参数: order_id change_amount ajax 改变价格的涨幅 ,总价格要从新运算一次
	 * 
	 */
	public void changeOrderPrice() {
		String order_id = getPara("order_id");
		Order order = Order.dao.findById(order_id);
		order.setChangeAmount(getPara("change_amount"));
		// fang 2016-07-19 有问题暂时未修改
		BigDecimal change_amount = new BigDecimal(getPara("change_amount"));
		order.setTotalAmount(order.getTotalAmount().add(change_amount));
		order.setModifiedTime(new Date());
		if (order.update()) {
			success();
		} else {
			fail();
		}
		/*
		 * BigDecimal a=new BigDecimal("+1.25"); BigDecimal b=new BigDecimal("5"); System.err.println(b.add(a));
		 */
	}

	/**
	 * fang 2016-06-22 修改 订单地址
	 * 
	 */
	public void changeAddress() {
		String order_id = getPara("order_id");
		Order order = Order.dao.findById(order_id);
		String express_address = getPara("express_address");
		order.setExpressAddress(express_address);
		order.setModifiedTime(new Date());
		if (order.update()) {
			success();
		} else {
			fail();
		}
	}

	/**
	 * fang 2016-06-22 修改规则 ItemOrder
	 * 
	 */
	public void changeSkuText() {
		String item_id = getPara("item_id");
		OrderItem orderItem = OrderItem.dao.findById(item_id);
		String sku_text = getPara("sku_text");
		orderItem.setSkuText(sku_text);
		Order order = Order.dao.findByIdLoadColumns(orderItem.getOrderId(), "id");
		order.setModifiedTime(new Date());
		order.update();
		if (orderItem.update()) {
			success();
		} else {
			fail();
		}
	}

	/**
	 * fang 2016-06-22 修改 admin (管理员)备注 order_id admin_remark
	 */
	public void changeRemark() {
		String order_id = getPara("order_id");
		String admin_remark = getPara("admin_remark");
		Order order = Order.dao.findById(order_id);
		order.setAdminRemark(admin_remark);
		order.setModifiedTime(new Date());
		if (order.update()) {
			success();
		} else {
			fail();
		}
	}

	/**
	 * fang 2016-06-23 发货
	 */
	public void addExpress() {
		String order_id = getPara("order_id");
		String express_name = getPara("express_name");
		String express_no = getPara("express_no");
		String type = getPara("type");//判断  新增还是修改
		if (express_name.equals("ziti")) {
			Order order = Order.dao.findById(order_id);
			order.setExpressName(express_name);
			order.setExpressNo(null);
			order.setState(OrderState.State_Express_OK);
			order.setModifiedTime(new Date());
			order.setExpressTime(new Date());
			order.update();
			success();
		}else {
			if ("change".equals(type)) {//修改
				Order order = new Order();
				order.setId(order_id);
				order.setExpressName(express_name);
				order.setExpressNo(express_no);
				order.setModifiedTime(new Date());
				order.update();
				/*对应的订单物流数据修改*/
				OrderExpress express = OrderExpress.dao.getOrderExpressByOrderId(order_id,0);
				express.setExpressCom(express_name);
				express.setExpressNo(express_no);
				express.setExpressPhone(null);
				express.setExpressState(-1);
				express.setContent(null);
				express.update();
				//物流缓存删除
				CacheUtils.del(WebConst.Order_Express+order_id+"_"+0);//删除原物流信息缓存
				CacheUtils.del(WebConst.Order_Express+order_id+"_"+1);//删除退货退款流信息缓存
				success("单号修改成功！");
			} else {//新增
				AjaxCmd cmd = Order.dao.send_express(order_id, express_no, express_name);
				renderJson(cmd);
			}
		}	
	}
	
	public void order_express(){
		String order_id = getPara("order_id");
		Integer type = getParaToInt("type",0);//1.正常发货物流信息 2.退货退款物流信息
		OrderExpress express = CacheUtils.get(WebConst.Order_Express+order_id+"_"+type);
		if (express == null) {
			express = OrderExpress.dao.getOrderExpressByOrderId(order_id,type);
			if (express==null) {
				fail("物流信息不存在！");
				return;
			}
			if (express.getExpressState()!=4) {//4已签收，不再调接口
				express.express_update();
			}
			CacheUtils.set(WebConst.Order_Express+order_id+"_"+type, express, WebConst.Order_Express_time);
		}
		success(express);
	}
	/**
	 * fang 2016-06-24 修改收货人电话,地址信息
	 */
	public void changeExpressPhone() {
		String order_id = getPara("order_id");
		String express_receive_name = getPara("express_receive_name");
		String express_address = getPara("express_address");
		String express_phone = getPara("express_phone");
		Order order = Order.dao.findById(order_id);
		order.setExpressAddress(express_address);
		order.setExpressPhone(express_phone);
		order.setExpressReceiveName(express_receive_name);
		order.setModifiedTime(new Date());
		// order.setState(OrderState.State_Express_OK);//发货成功
		if (order.update()) {
			success();
		} else {
			fail();
		}
	}

	/**
	 * 修改运费 fang 2016-07-21 注意: 根据 参数: order_id post_fee ajax 改变价格的涨幅 ,总价格要从新运算一次
	 * 
	 */
	public void changeOrderPostFee() {
		String order_id = getPara("order_id");
		Order order = Order.dao.findById(order_id);
		order.setExpressAmount(new BigDecimal(getPara("post_fee")));
		order.setTotalAmount(order.getItemAmount().add(new BigDecimal(getPara("post_fee"))));// 修改总价格
		order.setModifiedTime(new Date());
		if (order.update()) {
			success(order);
		} else {
			fail();
		}
	}

	/**
	 * 修改运费 fang 2016-07-21 注意: 根据 参数: order_id post_fee ajax 改变价格的涨幅 ,总价格要从新运算一次
	 * 
	 */
	public void changeOrderMoney() {
		String order_id = getPara("order_id");
		Order order = Order.dao.findById(order_id);
		order.setTotalAmount(new BigDecimal(getPara("total_fee")));// 修改总价格
		order.setModifiedTime(new Date());
		if (order.update()) {
			success(order);
		} else {
			fail();
		}
	}

	/**
	 * 查看自己的店铺订单统计
	 */
	public void shangjia_sum() {
		OrderSum sum = getModel(OrderSum.class, "sum");
		ShopInfo shop = getModel(ShopInfo.class, "shop");
		setAttr("shop", shop);
		String shop_id = ShopInfo.shop_id;
		paginate(OrderSum.dao.paginateShangjia(sum, shop, shop_id, getpage(), WebConst.Page_Size));
		render("order_sum.html");
	}

	//退款是否包含运费
	public void isAddFreight() {
		OrderItem orderItem = OrderItem.dao.getOrderItemById(getPara("itemId"));
		Order order = Order.dao.getOrderByOrderId(orderItem.getOrderId());
		
		BigDecimal price=orderItem.getPrice(); 
		BigDecimal expressAmount=order.getExpressAmount();
		int nums=orderItem.getNums();  
		BigDecimal product_amount=price.multiply(new BigDecimal(nums)); 
		boolean  isAddFreight=false;
		
		if (order.getExpressTime()==null&&expressAmount.compareTo(BigDecimal.ZERO)!=0) { //  未发货/不免运费 退运费 
			List<OrderItem> orderItem_list = OrderItem.dao.getItembyId(orderItem.getOrderId());
			int n = 0;
			for (int i = 0; i < orderItem_list.size(); i++) {
				if (orderItem_list.get(i).getRefundState() != 1) {
					n++;
				}
			}
			if (n == orderItem_list.size()-1) {  //此商品如是订单中商品全部退款的最后一个退款商品 退款金额(含运费) 
				OrderRefundApply orderRefundApply= OrderRefundApply.dao.findByOrderIsAddFreight(1, order.getId());
				OrderRefund orderRefund= OrderRefund.dao.findByOrderIsAddFreight(1,order.getId());
				if (orderRefundApply==null&&orderRefund==null) {
					isAddFreight=true;
					renderJson(new AjaxCmd(true,"含运费",isAddFreight));
					return;
				}
			}else if(n == orderItem_list.size()) {
				renderJson(new AjaxCmd(false,"该商品已不能主动退款!",isAddFreight));
				return;
			}
		}
		renderJson(new AjaxCmd(true,"不含运费",isAddFreight));
	}
	
	//是否使用优惠卷或兑换码 返回优惠金额(优惠卷,兑换码,首件立减,第二件立减)
	public void isPreferential() {
		OrderItem orderItem = OrderItem.dao.getOrderItemById(getPara("itemId"));
		Order order = Order.dao.getOrderByOrderId(orderItem.getOrderId());
		BigDecimal preferentialAmount=BigDecimal.ZERO;//优惠金额
		List<OrderItem> orderItem_list = OrderItem.dao.getItembyId(orderItem.getOrderId());
		//优惠卷兑换码金额
		if (orderItem_list.size()==1) {
			if (order.getCouponId()!=null) {
				preferentialAmount=order.getCouponAmount();
			}
			if (order.getPromoCode()!=null) {
				preferentialAmount=order.getPromoMoney();
			}
		}else {
			/*if (order.getCouponId()!=null) {
				UserCoupon coupon=UserCoupon.dao.findById(order.getCouponId());
				if (coupon!=null) {
					Promotional promotional=Promotional.dao.findById(coupon.getPromotionalId());
					if (promotional!=null) {
						if (promotional.getPlatformType()==2) {
							if (promotional.getUseId().equals(String.valueOf(orderItem.getProductId()))) {
								preferentialAmount=order.getCouponAmount();
							}
						}else {
							int n = 0;
							for (int i = 0; i < orderItem_list.size(); i++) {
								if (orderItem_list.get(i).getRefundState() != 1) {
									n++;
								}
							}
							if (n == orderItem_list.size()-1) {
								preferentialAmount=order.getCouponAmount();
							}
						}
					}
				}
			}*/
			/*if (order.getPromoCode()!=null) {
				PromoCode promoCode=PromoCode.dao.findById(order.getPromoCode());
				if (promoCode!=null) {
					PromoInfo promoInfo=PromoInfo.dao.findById(promoCode.getPromoInfoId());
					if (promoInfo!=null) {
						if (promoInfo.getProductId().equals(orderItem.getProductId())) {
							preferentialAmount=order.getPromoMoney();
						}
					}
				}
			}*/
		}
		
		//首页立减优惠
		if (order.getFirstDiscountMoney()!=null&&order.getFirstDiscountMoney().doubleValue()>0) {
			if (orderItem.getFirstDiscountMoney().doubleValue()>0) {
				preferentialAmount=preferentialAmount.add(orderItem.getFirstDiscountMoney());	
			}
		}
		
		//第二件立减优惠
		if (order.getSecondMoney()!=null&&order.getSecondMoney().doubleValue()>0) {
			if (orderItem.getSecondMoney().doubleValue()>0) {
				preferentialAmount=preferentialAmount.add(orderItem.getSecondMoney());
			}
		}
		
		success(preferentialAmount);
	}
	
	/**
	 * 主动退款
	 */
	@Before(Tx.class)
	public void activeRefund() {
		// type
		// 1.修改订单状态
		OrderItem orderItem = OrderItem.dao.findById(getPara("itemId"));
		Order order = Order.dao.findById(orderItem.getOrderId());
		if (order == null) {
			fail("此订单不存在！");
			return;
		}
		// 判断支付状态
		if (order.getPayState() != order.PayState_PayOk) {
			fail("订单支付状态异常！");
			return;
		}
		String refund_id = IdGenerateUtils.getOrderId();
		String out_refund_id = null;// 外部退款的流水编号
		boolean execute_state = false;// 执行的状态
		int total = (int) (Double.parseDouble(getPara("price")) * 100);// 退款金额
		
		if (order.getPayType() == 1 || order.getPayType() == 4) {
			// 微信支付的逻辑
			Map<String, String> para_map = new HashMap<String, String>();
			para_map.put("transaction_id", order.getTransactionId());
			para_map.put("out_refund_no", refund_id);// 生成退款的订单ID
			para_map.put("total_fee", order.getTotalFee() + "");// 订单总金额
			para_map.put("refund_fee", total + "");// 退款金额
			Map<String, String> result_map = null;
			if (order.getPayType() == 1) {
				para_map.put("appid", WxConfig.AppID);
				para_map.put("mch_id", WxConfig.WXMchid);
				para_map.put("op_user_id", WxConfig.WXMchid);// 操作员的ID
				result_map = PaymentApi.refund(para_map, WxConfig.WXKEY, WxConfig.KEYSTORE_FILE);
			} else {
				para_map.put("appid", WxConfig.APP_AppID);
				para_map.put("mch_id", WxConfig.APP_WXMchid);
				para_map.put("op_user_id", WxConfig.APP_WXMchid);// 操作员的ID
				result_map = PaymentApi.refund(para_map, WxConfig.APP_WXKEY, WxConfig.APP_KEYSTORE_FILE);
			}

			if (result_map == null) {
				fail("请求错误，请稍后再试！");
				return;
			}
			execute_state = result_map.get("result_code").equals("SUCCESS");
			if (!execute_state) {
				fail(result_map.get("err_code_des"));
				return;
			}
			out_refund_id = result_map.get("refund_id");
		} else if (order.getPayType() == 5) {
			// 支付宝支付
			AlipayTradeRefundResponse response = AlipaySDK.refund(order.getId(), order.getTotalAmount().toString());
			if (response == null) {
				fail("请求错误，请稍后再试！");
				return;
			}
			if (!response.isSuccess()) {
				// 判断如果执行失败
				fail(response.getMsg());
				return;
			}
			execute_state = true;
			out_refund_id = order.getId();
		}

		if (execute_state) {
			// 申请退款成功
			
			orderItem.setRefundState(OrderRefundApply.State_Finsh);
			orderItem.update();
			
			order.setJsAmount(order.getJsAmount().subtract(new BigDecimal(getPara("price"))));
			List<OrderItem> orderItem_list = OrderItem.dao.getItembyId(order.getId());
			
			int o = 0;
			for (int i = 0; i < orderItem_list.size(); i++) {
				if (orderItem_list.get(i).getRefundState() == 5) {
					o++;
				}
			}
			if (o == orderItem_list.size()) {  //所有商品退款完成
				order.setState(OrderState.State_Closed);
				/*if(order.getJsAmount().compareTo(BigDecimal.ZERO)==1){
					// 开始给供应商加钱
					if(ShopAccount.dao.Add_Money(order.getShopId(), order.getJsAmount().doubleValue())){
						// 出入日志
						ShopAccountTradeLog log = new ShopAccountTradeLog();
						log.setTradeId(IdGenerateUtils.getOrderId());
						log.setShopId(order.getShopId());
						log.setMoney(order.getJsAmount());
						log.setBusinessId(order.getId());
						log.setTradeTypeId(ShopAccountTradeType.Order_Income);
						log.save();
					}
				}*/
			}
			order.setModifiedTime(new Date());
			order.update();
			// 保存账单信息
			OrderRefund refund = new OrderRefund();
			refund.setRefundId(refund_id);
			refund.setOrderId(order.getId());
			refund.setItemId(orderItem.getItemId());
			refund.setRefundFee(total);
			refund.setRefundRecvAccout(AppConst.Pay_Type.get(order.getPayType()).toString());
			refund.setState(1);
			refund.setOutRefundNo(out_refund_id);
			refund.setIsAddFreight(getParaToInt("isAddFreight"));
			refund.setIsActiveRefund(1);//商家主动退款
			refund.save();
			
			//退款后 退积分
			/*Integer integral=(new BigDecimal(getPara("price")).setScale(1, BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(10))).intValue();
			UserAccount.addSubtractIntegral(order.getOpenid(),integral,UserIntegralLog.Operation_Subtract);
			UserIntegralLog.dao.addLog(order.getOpenid(),5,integral, UserIntegralLog.Operation_Subtract);*/

			// 执行分销代码 打款的代码 2017 12 25
			/*List<ChannelIncome> incomelist = ChannelIncome.dao.getIncomeByOrderId(order.getId());
			ShopFxConfig fxConfig=ShopFxConfig.dao.getShopFxInfoById(order.getShopId());
			Products pro = Products.dao.findByIdLoadColumns(orderItem.getProductId(), "channel_money");
			if (incomelist.size() > 0) {
				for (ChannelIncome income : incomelist) {
					if (income.getState() == ChannelIncome.State_Confirm_Wait) {
						BigDecimal distributionMoney=BigDecimal.ZERO;
					 	if(income.getType()==1){//分销退款金额
						  if (income.getIncomeLevel()==1) {
							   distributionMoney=pro.getChannelMoney().multiply(BigDecimal.valueOf(fxConfig.getRewardA())).divide(BigDecimal.valueOf(100)).multiply(BigDecimal.valueOf(orderItem.getNums()));
						  }else if(income.getIncomeLevel()==2) {
							 distributionMoney=pro.getChannelMoney().multiply(BigDecimal.valueOf(fxConfig.getRewardB())).divide(BigDecimal.valueOf(100)).multiply(BigDecimal.valueOf(orderItem.getNums()));
						  }
					    }else {//合伙人退款金额
						    distributionMoney=orderItem.getPrice().multiply(BigDecimal.valueOf(orderItem.getNums())).multiply(BigDecimal.valueOf(fxConfig.getRewardPartner())).divide(BigDecimal.valueOf(100));
					    }
						
						if ((income.getMoney().subtract(distributionMoney)).compareTo(BigDecimal.ZERO)==-1||(income.getMoney().subtract(distributionMoney)).compareTo(BigDecimal.ZERO)==0) {
							income.setState(ChannelIncome.State_Refund);// 修改分销日志状态为已经退款了
						}
						
						income.setMoney(income.getMoney().subtract(distributionMoney));
						income.setRefund(income.getRefund().add(distributionMoney));
						
						income.update();
						Db.update("update t_user_account set wait_money=wait_money-? where user_id=?", distributionMoney.doubleValue(), income.getUserId());// 修改账户的待确认金额
					}
				}
			}*/
			success("退款成功!");
		} else {
			fail("执行错误！");
		}
	}
	
	//佣金详情页
	public void commissionDetails() {
		setAttr("order_id",getPara());
		render("order_commission_detail.html");
	}
	
	//佣金详情页数据
	public void getCommissionDetails() {
		/*Page<ChannelIncome> page=ChannelIncome.dao.paginate(getpage(), getpageSize(),getPara("order_id"),getParaToInt("type"));
		Map<Object,Object> datamMap=new HashMap<Object, Object>();
		datamMap.put("page",page);
		datamMap.put("sumMoney", ChannelIncome.dao.getSumMoneyByOrderId(getPara("order_id")));
		renderJson(datamMap);*/
	}
	
}
